import SingleUpload from '@/components/SingleUpload';
import type { TagRecord } from '@/DatabaseType/Tag';
import { addTag, deleteTag, getTagList, updateTag } from '@/services/tag';
import {
  DEFAULT_REQUIRED_RULE,
  IMAGE_FALL_BACK,
  MODAL_TITLE_MAP,
} from '@/constant';
import { ResponseCode } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import {
  Button,
  Form,
  Image,
  Input,
  message,
  Modal,
  notification,
  Popconfirm,
} from 'antd';
import { useRef, useState } from 'react';

const TagManagement = () => {
  const actionRef = useRef<ActionType>();
  const [modalConfig, setModalConfig] = useState<{
    visible: boolean;
    type: 'edit' | 'view' | 'add';
    recordId?: number;
  }>({
    visible: false,
    type: 'add',
  });
  const [formInstance] = Form.useForm();
  const [operateLoading, setOperateLoadingLoading] = useState(false);

  const columns: ProColumns<TagRecord>[] = [
    {
      title: '主键',
      dataIndex: 'id',
      width: 75,
      align: 'center',
    },
    {
      title: '标签名称',
      dataIndex: 'name',
    },
    {
      title: '封面',
      dataIndex: 'coverUrl',
      render(text, { coverUrl }) {
        return (
          <Image
            style={{ objectFit: 'contain' }}
            width={60}
            height={60}
            src={coverUrl || IMAGE_FALL_BACK}
            alt="coverUrl"
            fallback={IMAGE_FALL_BACK}
          />
        );
      },
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (text, { id, name, coverUrl }) => [
        <a
          key="edit-detail"
          onClick={() => {
            // 打开弹窗
            setModalConfig((config) => ({
              ...config,
              visible: true,
              type: 'edit',
              recordId: id,
            }));
            formInstance.setFieldsValue({
              name,
              coverUrl,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete-detail"
          title="确认删除该记录吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => sureDelete(id)}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 确认删除
  async function sureDelete(id: number) {
    try {
      const { code, message: msg } = await deleteTag(id);
      if (code === ResponseCode.Success) {
        notification.success({ message: '删除成功' });
        actionRef.current?.reload();
      } else {
        notification.error({ message: msg || '删除失败' });
      }
    } catch (error: any) {
      notification.error({ message: error?.message || '删除品牌失败' });
    }
  }

  // proTable 获取角色列表方法
  async function request(params: any) {
    try {
      const { code, data, message: msg } = await getTagList(params);
      if (code === ResponseCode.Success) {
        return {
          data: data.list,
          total: data.total,
        };
      }
      throw new Error(msg);
    } catch (error: any) {
      message.error(error?.message);
      return {
        data: [],
        total: 0,
      };
    }
  }

  // 弹窗点击确认，提交表单
  async function sureAdd() {
    switch (modalConfig.type) {
      // 新增时
      case 'add': {
        // 获取表单数据
        const formData = await formInstance.validateFields();
        // 弹窗确认按钮loading
        setOperateLoadingLoading(true);
        try {
          const {
            code,
            data: newRecordId,
            message: msg,
          } = await addTag(formData);
          if (code === ResponseCode.Success) {
            setModalConfig((config) => ({ ...config, visible: false }));
            actionRef.current?.reload();
            notification.success({
              message: `新增ID: ${newRecordId}成功`,
            });
          } else {
            notification.error({ message: msg || '新增品失败' });
          }
        } catch (error: any) {
          notification.error({ message: error?.message || '新增失败' });
        }
        setOperateLoadingLoading(false);
        break;
      }
      // 修改时
      case 'edit': {
        const formData = await formInstance.validateFields();
        setOperateLoadingLoading(true);
        try {
          const { code, message: msg } = await updateTag(
            modalConfig.recordId as number,
            formData,
          );
          if (code === ResponseCode.Success) {
            setModalConfig((config) => ({ ...config, visible: false }));
            actionRef.current?.reload();
            notification.success({ message: `更新成功` });
          } else {
            notification.error({ message: msg || '更新失败' });
          }
        } catch (error: any) {
          notification.error({ message: error?.message || '更新失败' });
        }
        setOperateLoadingLoading(false);
        break;
      }
      // 查看时
      case 'view':
        setModalConfig((config) => ({ ...config, visible: false }));
        break;
    }
  }

  return (
    <PageContainer className="tag-management">
      <ProTable<TagRecord>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          return request(params);
        }}
        scroll={{
          x: 1200,
        }}
        rowKey="id"
        search={{
          labelWidth: 100,
          defaultCollapsed: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            key="add-detail"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              formInstance.resetFields();
              setModalConfig((config) => ({
                ...config,
                visible: true,
                type: 'add',
              }));
            }}
          >
            新增
          </Button>,
        ]}
      />
      <Modal
        title={MODAL_TITLE_MAP[modalConfig.type]}
        open={modalConfig.visible}
        onCancel={() =>
          setModalConfig((config) => ({
            ...config,
            visible: false,
            userId: undefined,
          }))
        }
        onOk={sureAdd}
        confirmLoading={operateLoading}
      >
        <Form
          labelCol={{ span: 4 }}
          form={formInstance}
          disabled={modalConfig.type === 'view'}
        >
          <Form.Item name="name" label="名称" rules={DEFAULT_REQUIRED_RULE}>
            <Input maxLength={63} showCount />
          </Form.Item>
          <Form.Item name="coverUrl" label="封面">
            <SingleUpload />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default TagManagement;
